/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.web;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.entity.Advance;
import com.jeeplus.modules.ap.entity.Income;
import com.jeeplus.modules.ap.entity.Yue;
import com.jeeplus.modules.ap.service.YueService;
import com.jeeplus.modules.ap.util.Export;
import com.jeeplus.modules.fee.entity.Bill;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.ap.entity.BillAdd;
import com.jeeplus.modules.ap.service.BillAddService;

/**
 * 运单附加费Controller
 * @author 李超辉
 * @version 2018-05-30
 */
@Controller
@RequestMapping(value = "${adminPath}/ap/billAdd")
public class BillAddController extends BaseController {

	@Autowired
	private BillAddService billAddService;
	@Autowired
	private YueService yueService;
	@ModelAttribute
	public BillAdd get(@RequestParam(required=false) String id) {
		BillAdd entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = billAddService.get(id);
		}
		if (entity == null){
			entity = new BillAdd();
		}
		return entity;
	}
	
	/**
	 * 运单附加费列表页面
	 */
	@RequiresPermissions("ap:billAdd:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/ap/billAddList";
	}
	/**
	 * 运单附加费列表页面
	 */
	@RequiresPermissions("ap:billAdd:list")
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/ap/2/billAddList";
	}
	
//		/**
//	 * 运单附加费列表数据
//	 */
//	@ResponseBody
//	@RequestMapping(value = "cx")
//	public String  data(BillAdd b,HttpServletRequest request, String min,String max,String pro,String c,String s) {
//		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
//			b.setPro(pro);
//		}else{
//			if(!UserUtils.getUseroffice().equals("总部")){
//				b.setPro(UserUtils.getUseroffice());
//			}
//		}
//
//		b.setMin(min);
//		b.setMax(max);
//		b.setZydh(c);
//		b.setStatus(s);
//		List<BillAdd> list=billAddService.findList(b);
//		double fhpsr=0.0;
//		double fhpzc=0.0;
//		double xxf=0.0;
//		double bxf=0.0;
//		double qtsr=0.0;
//		double zxf=0.0;
//		double qtzc=0.0;
//		String ids="";
//		for(BillAdd bill:list){
//            fhpsr+=Double.parseDouble(bill.getFhpsr());
//			fhpzc+=Double.parseDouble(bill.getFhpzc());
//			bxf+=Double.parseDouble(bill.getBxfsr());
//			xxf+=Double.parseDouble(bill.getXxfsr());
//			qtsr+=Double.parseDouble(bill.getQtsr());
//			zxf+=Double.parseDouble(bill.getZxfzc());
//			qtzc+=Double.parseDouble(bill.getQtzc());
//			ids+=bill.getId()+",";
//		}
//		b.setFhpsr(fhpsr+"");
//		b.setFhpzc(fhpzc+"");
//		b.setBxfsr(bxf+"");
//		b.setXxfsr(xxf+"");
//		b.setQtsr(qtsr+"");
//		b.setZxfzc(zxf+"");
//		b.setQtzc(qtzc+"");
//		b.setMax(ids);
//		list.add(b);
//		Gson g=new Gson();
//		return g.toJson(list).toString();
//	}
	/**
	 * 预付款列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:damaged:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(BillAdd billAdd, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!UserUtils.getUseroffice().equals("总部")){
			billAdd.setPro(UserUtils.getUseroffice());
		}
		Page<BillAdd> page = billAddService.findPage(new Page<BillAdd>(request, response), billAdd);
		return getBootstrapData(page);
	}
	/**
	 * 预付款列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:damaged:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(BillAdd billAdd, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!UserUtils.getUseroffice().equals("总部")){
			billAdd.setPro(UserUtils.getUseroffice());
		}
		billAdd.setStatus("已入账");
		Page<BillAdd> page = billAddService.findPage(new Page<BillAdd>(request, response), billAdd);
		return getBootstrapData(page);
	}
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequestMapping(value = "daochu")
	public void daochu0(HttpServletResponse response,String ids) {
		//获取数据
		String[] idd=ids.split(",");
		List<BillAdd> list =new ArrayList<BillAdd>();
		for(String id:idd){
			list.add(billAddService.get(id));
		}

		Export e=new Export();
		e.exportbillAdd(response,list);
	}
	/**
	 * 查看，增加，编辑运单附加费表单页面
	 */
	@RequiresPermissions(value={"ap:billAdd:view","ap:billAdd:add","ap:billAdd:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(BillAdd billAdd, Model model) {
		String pro= UserUtils.getUseroffice();
		if(pro!="总部"){
			billAdd.setPro(pro);
		}
		billAdd.setStatus("未过账");
		model.addAttribute("billAdd", billAdd);
		return "modules/ap/billAddForm";
	}

	/**
	 * 保存运单附加费
	 */
	@ResponseBody
	@RequiresPermissions(value={"ap:billAdd:add","ap:billAdd:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(BillAdd billAdd, Model model,HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
		String s=request.getParameter("date");
		billAdd.setDate(sim.parse(s));
		if (!beanValidator(model, billAdd)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		billAddService.save(billAdd);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存运单附加费成功");
		return j;
	}
	/**
	 * 确认入账
	 */
	@ResponseBody
	@RequestMapping(value = "rz")
	public AjaxJson rz(BillAdd billAdd, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		NumberFormat nf = NumberFormat.getInstance();
		//操作办事处余额
		Yue yue=yueService.findUniqueByProperty("pro",UserUtils.getUseroffice());
		Double l=Double.parseDouble(billAdd.getXxfsr())+Double.parseDouble(billAdd.getBxfsr())+Double.parseDouble(billAdd.getFhpsr())+Double.parseDouble(billAdd.getQtsr())-Double.parseDouble(billAdd.getFhpzc())-Double.parseDouble(billAdd.getZxfzc())-Double.parseDouble(billAdd.getQtzc());
		yue.setXj(nf.format(Double.parseDouble(yue.getXj())+l).replaceAll(",",""));
		yue.setZje(nf.format(Double.parseDouble(yue.getZje())+l).replaceAll(",",""));
		yueService.save(yue);
		billAdd.setStatus("已入账");
		billAdd.setRz(new Date());
		billAddService.save(billAdd);
		j.setMsg("确认入账成功");
		return j;
	}
	/**
	 * 删除运单附加费
	 */
	@ResponseBody
	@RequestMapping(value = "delete")
	public AjaxJson delete(BillAdd billAdd, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		billAddService.delete(billAdd);
		j.setMsg("删除运单附加费成功");
		return j;
	}
	
	/**
	 * 批量删除运单附加费
	 */
	@ResponseBody
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			billAddService.delete(billAddService.get(id));
		}
		j.setMsg("删除运单附加费成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("ap:billAdd:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(BillAdd billAdd, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "运单附加费"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<BillAdd> page = billAddService.findPage(new Page<BillAdd>(request, response, -1), billAdd);
    		new ExportExcel("运单附加费", BillAdd.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出运单附加费记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("ap:billAdd:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<BillAdd> list = ei.getDataList(BillAdd.class);
			for (BillAdd billAdd : list){
				try{
					billAddService.save(billAdd);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条运单附加费记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条运单附加费记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入运单附加费失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/billAdd/?repage";
    }
	
	/**
	 * 下载导入运单附加费数据模板
	 */
	@RequiresPermissions("ap:billAdd:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "运单附加费数据导入模板.xlsx";
    		List<BillAdd> list = Lists.newArrayList(); 
    		new ExportExcel("运单附加费数据", BillAdd.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/billAdd/?repage";
    }

}